<template>
  <div class="infolist p-2">
    <div class="top-one">
      <el-card style="width:100%">
        <template #header>
          <div class="card-header">
            <span>发票详情</span>
          </div>
        </template>
        <div class="p-4">
          <el-row :gutter="20" class="row-bg" justify="space-between">
          <el-col :span="6"><span>创建时间：</span>{{infoMessage.addTime}}</el-col>
          <el-col :span="6"><span>服务商名称：</span>{{infoMessage.sydName}}</el-col>
          <el-col :span="6"><span>服务商编号：</span>{{infoMessage.sydNo}}</el-col>
        </el-row>
        <el-row :gutter="20" class="row-bg" justify="space-between">
          <el-col :span="6"><span>企业名称：</span>{{infoMessage.merName}}</el-col>
          <el-col :span="6"><span>企业编号：</span>{{infoMessage.merNo}}</el-col>
          <el-col :span="6"><span>企业电话：</span>{{infoMessage.dwdh}}</el-col>
        </el-row>
        <el-row :gutter="20" class="row-bg" justify="space-between">
          <el-col :span="6"><span>纳税人识别号：</span>{{infoMessage.creditCode}}</el-col>
          <el-col :span="6"><span>企业注册地址：</span>{{infoMessage.dwzcdz}}</el-col>
          <el-col :span="6"><span>发票抬头：</span>{{infoMessage.merName}}</el-col>
        </el-row>
        <el-row :gutter="20" class="row-bg" justify="space-between">
          <el-col :span="6"><span>开票银行：</span>{{infoMessage.bankCard}}</el-col>
          <el-col :span="6"><span>开票银行账号：</span>{{infoMessage.bankCard}}</el-col>
          <el-col :span="6"><span>开票项目：</span>{{infoMessage.category}}</el-col>
        </el-row>
        <el-row :gutter="20" class="row-bg" justify="space-between">
          <el-col :span="6"><span>发票数量：</span>{{infoMessage.invNum}}</el-col>
          <el-col :span="6"><span>开票金额：</span> {{proxy?.convertFenToYuan(infoMessage.invAmount)}}</el-col>
          <el-col :span="6"><span>备注：</span>{{infoMessage.remark}}</el-col>
        </el-row>
        <el-row :gutter="20" class="row-bg" justify="space-between">
          <el-col :span="6"><span>开票状态：</span>
            <span class="activebet" v-if="infoMessage.status == 1">待开票</span>
            <span class="activebet" v-else-if="infoMessage.status == 2">已开票</span>
            <span class="activebet" v-else-if="infoMessage.status == 3">已取消</span>
            <span class="activebet" v-else-if="infoMessage.status == 4">驳回</span>
            <span class="activebet" v-else-if="infoMessage.status == 5">开票中</span>
          </el-col>

        </el-row>
        </div>
      </el-card>
    </div>
    <div class="top-two mt-3">
      <el-card style="width:100%">
        <template #header>
          <div class="card-header">
            <span>批次列表</span>
          </div>
        </template>
        <div class="towtabbal">
          <el-table ref="roleTableRef" v-loading="loading" border :data="invoiceBoll" style="width:100%" >
            <el-table-column label="创建时间" align="center" prop="createTime" width="200"/>
            <el-table-column label="企业名称" align="center" prop="merName" width="220" show-overflow-tooltip/>
            <el-table-column label="服务商" align="center" prop="sydName" width="220" show-overflow-tooltip/>
            <el-table-column label="批次流水号" align="center" prop="billNo" width="220" show-overflow-tooltip/>
            <el-table-column label="批次状态" align="center" prop="date">
              <template #default="scope">
                <div>
                  <span v-if="scope.row.billStatus == 1">发放成功</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="总金额（元）" align="center" prop="invAmount" >
              <template #default="scope">
                   {{proxy?.convertFenToYuan(scope.row.invAmount)}}
               </template>
              </el-table-column>
            <el-table-column label="服务费（元）" align="center" prop="serviceChargeAmount" >
              <template #default="scope">
                   {{proxy?.convertFenToYuan(scope.row.serviceChargeAmount)}}
               </template>
              </el-table-column>
            <el-table-column label="实际打款金额（元）" align="center" prop="money" >
              <template #default="scope">
                  {{proxy?.convertFenToYuan(scope.row.invAmount) - proxy?.convertFenToYuan(scope.row.serviceChargeAmount)}}
              </template>
             </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
          </el-table>
        </div>
        <div class="demo-pagination-block mt-[20px]">
          <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :small="true"
            :disabled="false"
            :background="false"
            layout="sizes, prev, pager, next"
            :total="total"
            @size-change="wayinvoiceBilllist"
            @current-change="wayinvoiceBilllist"
          />
        </div>
      </el-card>
    </div>
    <div class="top-two mt-3" v-if="!type || type== 'add' || type== 'mdy'">
      <el-card style="width:100%">
        <template #header v-if="!type || type== 'mdy'">
          <div class="card-header">
            <span>发票列表</span>
          </div>
        </template>

        <template #header v-if="type == 'add'">
          <div class="card-header">
            <el-button type="primary" @click="uploadIn">上传发票</el-button>
          </div>
        </template>


        <div class="towtabbal">
          <el-table ref="roleTableRef" v-loading="loading" border :data="infoListdata" style="width:100%" >
            <el-table-column label="发票编号" align="center" prop="detailNo" show-overflow-tooltip/>
            <el-table-column label="发票金额" align="center" prop="invAmount" show-overflow-tooltip>
              <template #default="scope">
                   {{proxy?.convertFenToYuan(scope.row.invAmount)}}
               </template>
            </el-table-column>
            <el-table-column label="服务项目" align="center" prop="category" show-overflow-tooltip/>
            <el-table-column label="发票样张" align="center" width="220">
              <template #default="scope">
                <ImagePreview
                  v-if="scope.row.invPic"
                  :width="50"
                  :height="50"
                  :src="scope.row.invPic"
                  :preview-src-list="[scope.row.invPic]"
                />
                <!-- <el-link :href="scope.row.invPic" type="primary" target="_blank" v-if="type != 'add'">查看发票</el-link>
                <el-tag link  v-if="type == 'add'" @click="upMdy(scope.row)">修改</el-tag>
                <el-tag link  v-if="type == 'add'"  @click="upDel(scope.row)">删除</el-tag>-->
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="220" v-if="type == 'add'" >
              <template #default="scope">
                <el-link :href="scope.row.invPic" type="primary" target="_blank" v-if="type != 'add'">查看发票</el-link>
                <el-tag link  v-if="type == 'add'" @click="upMdy(scope.row)">修改</el-tag>
                <el-tag link  v-if="type == 'add'"  @click="upDel(scope.row,scope.$index)">删除</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="220" v-if="type == 'mdy'" >
              <template #default="scope">
                <el-tag link   @click="mdy(scope.row)">修改</el-tag>
              </template>
            </el-table-column>

          </el-table>
          <el-row justify="center" class="mt-14" v-if="type == 'add'" >
            <el-button plain @click="back">返回</el-button>
            <el-button type="primary" :loading="submitloading" @click="addInv()">提交</el-button>
          </el-row>

          <el-row justify="center" class="mt-14" v-if="type == 'mdy'" >
            <el-button plain @click="back">返回</el-button>
          </el-row>

        </div>
      </el-card>
    </div>
    <div class="top-one mt-3">
      <el-card style="width:100%" v-if="!type">
        <template #header>
          <div class="card-header">
            <span>快递信息</span>
          </div>
        </template>
        <div class="p-4">
          <el-row :gutter="20" class="row-bg" justify="space-between">
          <el-col :span="6"><span>发票收件人：</span>{{infoMessage.addName}}</el-col>
          <el-col :span="6"><span>收件人电话：</span>{{infoMessage.addPhone}}</el-col>
          <el-col :span="6"><span>收件地址：</span>{{ infoMessage.addAddress }}</el-col>
        </el-row>
        <el-row :gutter="20" class="row-bg" justify="space-between">
          <el-col :span="6"><span>快递时间：</span>{{ infoMessage.iogisticsTime }}</el-col>
          <el-col :span="6"><span>快递公司：</span>{{ infoMessage.iogisticsCompany }}</el-col>
          <el-col :span="6"><span>快递编号：</span>{{ infoMessage.iogisticsNo }}</el-col>
        </el-row>
        <el-row :gutter="20" class="row-bg" justify="space-between">
          <el-col :span="6"><span>快递状态：</span>
            <span class="activebet" v-if="infoMessage.iogisticsStatus == 1">未寄出</span>
            <span class="activebet" v-else-if="infoMessage.iogisticsStatus == 2">未签收</span>
            <span class="activebet" v-else-if="infoMessage.iogisticsStatus == 3">已签收</span>

          </el-col>
        </el-row>
        <el-row justify="center" class="mt-14">
          <el-button plain @click="back">返回</el-button>
        </el-row>
        </div>
      </el-card>

      <el-card style="width:100%" v-if="type == 'np'">
        <template #header>
          <div class="card-header">
            <span>发票申请驳回</span>
          </div>
        </template>
        <div class="p-4">
           <el-form :model="mdyForm"  :rules="mdyRules"  ref="dialogRef" label-width="120px" label-suffix=":">
             <el-form-item label="审核意见" prop="remarer">
               <el-input v-model="mdyForm.remarer" type="textarea"  :rows="6" />
             </el-form-item>
           </el-form>
        <el-row justify="center" class="mt-14">
          <el-button plain @click="back">返回</el-button>
          <el-button type="primary" :loading="submitloading" @click="submit('np')">确定</el-button>
        </el-row>
        </div>
      </el-card>



      <el-card style="width:100%" v-if="type == 'addKd' || type== 'mdyKd'">
        <template #header>
          <div class="card-header">
            <span>快递信息</span>
          </div>
        </template>
        <div class="p-4">
           <el-form :model="kdForm"  :rules="kdRule"  ref="kdRef" label-width="120px" label-suffix=":">
             <el-row :gutter="20">
               <el-col :span="8">
                  <el-form-item label="快递编号" prop="iogisticsNo">
                    <el-input v-model="kdForm.iogisticsNo"   placeholder="请输入快递编号"
                  clearable />
                  </el-form-item>
                </el-col>
              <el-col :span="8">
                 <el-form-item label="快递公司" prop="iogisticsCompany">
                   <el-select v-model="kdForm.iogisticsCompany" placeholder="请选择快递公司" style="width:100%">
                     <el-option :label="item.value" :value="item.value" v-for="(item,index) in express_list" :key="index" />
                   </el-select>
                 </el-form-item>
               </el-col>
            </el-row>
            </el-form>
          <el-row justify="center" class="mt-14">
            <el-button plain @click="back">返回</el-button>
            <el-button type="primary" :loading="submitloading" @click="submitKd('np')">确定</el-button>
          </el-row>
        </div>
      </el-card>


    </div>



    <!-- 添加发票 -->
        <el-dialog
          v-model="infoEditVisible"
          title="添加发票"
          width="800px"
        >
          <el-form
            ref="infoEditFormRef"
            :model="infoEditForm"
            :rules="infoEditFormRules"
            label-width="auto"
          >
          <el-row :gutter="20">

            <el-col :span="12">
              <el-form-item
                label="发票编号"
                prop="detailNo"
                required
              >
                <el-input
                  v-model="infoEditForm.detailNo"
                  placeholder="请输入发票编号"
                  clearable
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item
                label="发票金额："
                prop="invAmount"
                required
              >
                <el-input
                  v-model="infoEditForm.invAmount"
                  type="number"
                  placeholder="请输入发票金额"
                  clearable
                  style="width: 100%;"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="开票类目："
                prop="category"
                required
              >
                <el-select v-model="infoEditForm.category" placeholder="请选择开票项目" style="width:100%">
                  <el-option :label="item.type" :value="item.id" v-for="(item,index) in invoiceTypeList" :key="index" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="发票样张："
                prop="invPic"
              >
                <imageUpload
                  v-model="infoEditForm.invPic"
                  required
                  modelKey="url"
                  :limit="1"
                  :isShowTip="false"
                />
              </el-form-item>
            </el-col>
          </el-row>

          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="infoEditVisible = false">关 闭</el-button>
              <el-button
                type="primary"
                @click="infoEditSubmit"
              >确 定</el-button>
            </div>
          </template>
        </el-dialog>


  </div>
</template>

<script setup name="infolist" lang="ts">
  import { ref ,reactive} from "vue";
  import { invoiceInfo , invoiceBilllist,reject,uploadInvoice,mdyDetail,mdyInvoice } from '@/api/invoice/record/index'
  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  const { express_list } = toRefs<any>(proxy?.useDict('express_list'));
  const route = useRoute();
  const router = useRouter();
  const submitloading = ref(false)
  const dialogRef = ref();
  const info_id = ref(route.query.id as string)
  const loading = ref(false); //批次列表加载动画
  const invoiceTypeList = ref([])
  // 获取页面详情
  const infoMessage = ref({})
  const infoListdata = ref([]) //发票列表
  const kdRef = ref()
  const mdyForm = ref({
    remarer:''
  })

  const kdForm = ref({
      iogisticsCompany:'',
      iogisticsNo:''
  })


  const kdRule = ref({
    iogisticsNo: [{ required: true, message: '请输入快递单号', trigger: 'blur' }],
    iogisticsCompany: [{ required: true, message: '请选择快递公司', trigger: 'change' }],
  });

  const mdyTag = ref(false);

  const invAmountValidation = (rule: any, value: number, callback: any) => {

    let y = proxy?.convertFenToYuan(infoMessage.value.invAmount);
    if (parseFloat(value) > y ) {
      callback(new Error("开票金额不能大于"+ y));
    }
    let sum = parseFloat(value);
    if(mdyTag.value){
        sum  = 0;
    }
    infoListdata.value.forEach(item=>{
        sum = sum + item.invAmount/100;
    })

  if (sum > y ) {
      callback(new Error("开票总额不能大于"+ y));
    } else {
      callback();
    }



  };


//添加快递
const submitKd= ()=>{

  kdRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        submitloading.value = true;
            mdyInvoice({
              id:info_id.value,
              ...kdForm.value
            }).then(res=>{
              ElMessage({
                type: 'success',
                message: '提交成功'
              });
              returnOn();
            }).finally(()=>{
              submitloading.value = false;
            });
        }
      }
    )
}

  const upMdy = (row)=>{
    mdyTag.value =true;
      infoEditForm.value = {
        detailNo:row.detailNo,
        invAmount:row.invAmount/100,
        invPic:row.invPic,
        category:row.category
      }
      infoEditVisible.value  = true;
  }

  const mdyRow = ref()
  const mdy = (row)=>{
      mdyTag.value =true;
      infoEditForm.value = {
        detailNo:row.detailNo,
        invAmount:row.invAmount/100,
        invPic:row.invPic,
        category:row.category
      }
      mdyRow.value = row;
      infoEditVisible.value  = true;
  }

  const upDel = (row,index)=>{
     mdyTag.value =false;
    infoListdata.value.splice(index, 1);
  }

const infoEditFormRules = ref({
  detailNo: [{ required: true, message: '请输入发票编号', trigger: 'blur' }],
  invAmount: [{ required: true, message: '请输入开票金额', trigger: 'blur' }
  , {
    required: true,
    validator: invAmountValidation,
    trigger: "blur"
  }
  ],
  category: [{ required: true, message: '请选择开票类目', trigger: 'change' }],
  invPic: [{ required: true, message: '请上传发票', trigger: 'blur' }],
});


  const infoEditForm = ref({
    invNo:'',
    detailNo:'',
    invAmount:null,
    invPic:'',
    category:''

  });

  const infoEditVisible = ref(false);

// 返回
const returnOn = () => {
  proxy?.$router.go(-1);
  proxy?.$tab.closePage(route);
};

const addInv =()=>{
    if(infoListdata.value.length == 0){
        ElMessage({
          type: 'error',
          message: '请先上传发票'
        });
      return;
    }
  submitloading.value = true;
    uploadInvoice({
      id:info_id.value,
      details:infoListdata.value
    }).then(res=>{
        if(res.code == 200){
            ElMessage({
              type: 'success',
              message: '提交成功'
            });
            returnOn();
        }
    }).finally(()=>{
        submitloading.value = false;
    })


}



   const mdyRules = ref({
      remarer: [{ required: true, message: "请输入驳回原因", trigger: "blur" }],
  });

 const infoEditFormRef = ref();
  const infoEditSubmit = ()=>{
    infoEditFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {

        if(type.value !== 'mdy'){

          infoListdata.value.push({
              invNo:infoMessage.value.no,
              invId:infoMessage.value.id,
              ...infoEditForm.value,
              invAmount:infoEditForm.value.invAmount*100
          });
          infoEditForm.value = {
            invNo:'',
            detailNo:'',
            invAmount:null,
            invPic:'',
            category:''
          }

        }else{
          let params = {
            id:mdyRow.value.id,

            ...infoEditForm.value,
            invNo:mdyRow.value.invNo,
            invAmount:infoEditForm.value.invAmount*100
          }
          mdyDetail(params).then(res=>{
              ElMessage({
                type: 'success',
                message: '修改成功'
              });
              wayinvoiceInfo()
          })
        }
          infoEditVisible.value  = false;

      }

  })
}


  const wayinvoiceInfo = async ()=>{
    const res = await invoiceInfo(info_id.value)
    infoMessage.value = res.data;
    invoiceTypeList.value.push({
      id:infoMessage.value.category,
      type:infoMessage.value.category
    });

    if(type.value == 'mdyKd'){

      kdForm.value = {
        iogisticsCompany:infoMessage.value.iogisticsCompany,
        iogisticsNo:infoMessage.value.iogisticsNo
      }


    }


    infoListdata.value = res.data.details as Array
  }
  // 查看批次列表
  const pageSize = ref(10)
  const pageNum = ref(1)
  const total = ref(0)
  const invoiceBoll = ref([])   //列表参数
  const wayinvoiceBilllist = async ()=>{
    const res = await invoiceBilllist({
      invId:info_id.value,
      pageSize:pageSize.value,
      pageNum:pageNum.value
    })
    invoiceBoll.value = res.rows
    total.value = res.total
  }


  //上传发票
  const uploadIn = ()=>{
    mdyTag.value =false;
    infoEditVisible.value  = true;
  }

  // 返回上一页
  const back = ()=>{
    // router.go(-1)
    returnOn();
  }

  const submit = (type:any)=>{

    if(type == 'np'){
      //驳回
        dialogRef.value?.validate(async (valid: boolean) => {
          if (valid) {
            submitloading.value = true;
              reject({
                id:info_id.value,
                remark:mdyForm.value.remarer
              }).then(res=>{
                  if(res.code == 200){
                      ElMessage({
                        type: 'success',
                        message: '提交成功'
                      });
                      returnOn();
                  }
              }).finally(()=>{
                submitloading.value  = false;
              })

          }});
    }
  }

  const type = ref();
  onMounted(()=>{
    if(route.query){
        type.value = route.query.type;
    }
    wayinvoiceInfo()
    wayinvoiceBilllist()
  })
</script>

<style lang="scss" scoped>
.infolist {
  background-color: #eef0f3;
  .card-header{
    font-size: 14px;
    font-weight: bold;
  }
  .demo-pagination-block{
    float: right;
    padding-bottom: 20px;

  }
  .top-one {
    .el-row {
      margin-bottom: 14px;
    }
    .el-col {
      font-size: 14px;
      color:#666;
      span{
        color:#000
      }
      .activebet{
        padding: 4px 8px;
        border-radius: 5px;
        margin-left: 10px;
        font-size: 12px;
        background: #e2fffb;
        border:1px solid #87e8de;
      }
    }
  }
}
</style>
